﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
using System.Windows.Forms;

public class RunAsAdministrator
{
    public static bool IsRunAsAdministrator()
    {
        var windowsIdentity = WindowsIdentity.GetCurrent();
        var windowsPrincipal = new WindowsPrincipal(windowsIdentity);
        return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
    }

    /// <summary>
    ///   if (IsRunAsAdministrator()) return true;
    /// </summary>
    /// <param name="displayMessage"></param>
    /// <returns></returns>
    public static bool ValidateAdministratorModeAndRestart(bool displayMessage)
    {
        if (IsRunAsAdministrator()) return true;
        else
        {
            if (displayMessage)
            {
                var fi = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
                string productName = fi.FileDescription;
                MessageBox.Show(string.Format("{0} se lanzará con privilegios de administrador.", productName), "Atención", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            try
            {
                //using (Process a = new Process())
                //{
                //    {
                //        a.StartInfo.Arguments = "-s";
                //        a.StartInfo.FileName = Assembly.GetExecutingAssembly().FullName;

                //        a.Start();
                //        a.WaitForExit();
                //        //Espera a que el proceso termine.
                //    }
                //}
                //Application.Current.Shutdown();
                //System.Windows.Forms.Application.Exit();

                var processInfo = new ProcessStartInfo
                {
                    FileName = Assembly.GetExecutingAssembly().Location,
                    UseShellExecute = true,
                    Verb = "runas"
                };

                try
                {
                    Process p = Process.Start(processInfo);
                    p.WaitForExit();
                }
                catch (Exception)
                {
                    //Do nothing. Probably the user cancelled the UAC window or provided invalid credentials.
                }

                Application.Exit();
            }
            catch (Exception e)
            {
                MessageBox.Show(String.Format("Lo sentimos, esta aplicación se debe ejecutar como administrador. Ruta: '{0}'. Error: {1}",
                                              Assembly.GetExecutingAssembly().Location, e.Message));
            }
            return false;
        }
    }
}
